<?php
/**
 * @title:
 * @desc:
 * @since：2019/7/2 0002  上午 9:45
 */
namespace app\http\middleware;

use app\model\Authrule;
use app\model\Role;
use app\model\RoleAdmin;
use app\model\RoleAuthrule;
use think\facade\Config;
use app\common\logic\Base;
use app\common\tools\ReturnCode;


class AdminPermission extends Base
{
    /**
     * 用户权限检测
     */
    public function handle($request, \Closure $next) {
        $userInfo = $request->API_ADMIN_USER_INFO;
        $userInfo['id'] = 1;

        $header = Config::get('apiadmin.CROSS_DOMAIN');

/*
        $groups = (new RoleAdmin())->where("admin_id",1)->column("role_id");

        //没有禁用的角色
        $groups = (new Role())->whereIn("role_id",$groups)->where("status",0)->column("role_id");


        $allRules = (new RoleAuthrule())->whereIn('role_id', $groups)->column("rule_id");
        return $this->buildFailed($allRules, ReturnCode::FORBIDDEN_ACTION[1])->header($header);*/



        $rule = (new Authrule())->where("name",$request->path())->find();

        if (isset($rule) && $rule["rule_id"]) {

            if (!$this->checkAuth($userInfo['id'], $rule["rule_id"])) {
                return $this->buildFailed(ReturnCode::FORBIDDEN_ACTION[0], ReturnCode::FORBIDDEN_ACTION[1]);//->header($header);
            }
        }

        return $next($request);
    }

    /**
     * 检测用户权限
     */
    private function checkAuth($admin_id, $rule_id) {
        $isSupper = false;//Tools::isAdministrator($admin_id);
        if (!$isSupper) {
            $rules = $this->getAuth($admin_id);

            return in_array($rule_id, $rules);
        } else {
            return true;
        }

    }

    /**
     * 根据用户ID获取全部权限节点
     */
    private function getAuth($admin_id) {

/*        $findAuthRuleCount = Db::name('auth_rule')->where([
            'name' => $name
        ])->count();

        if ($findAuthRuleCount == 0) {//没有规则时,不验证!
            return true;
        }*///$groups = AdminAuthGroupAccess::get(['uid' => $uid]);
        $groups = (new RoleAdmin())->where("admin_id",$admin_id)->column("role_id");

        //没有禁用的角色
        $groups = (new Role())->whereIn("role_id",$groups)->where("status",0)->column("role_id");

        if (isset($groups)) {

            $allRules = (new RoleAuthrule())->whereIn('role_id', $groups)->column("rule_id");

            if (isset($allRules)) {
                return $allRules;
            } else {
                return [];
            }
        }
    }


}